﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

// http://gdata.youtube.com/feeds/api/users/zhoudevsky/uploads
// https://developers.google.com/youtube/2.0/developers_guide_protocol_understanding_video_feeds

namespace DevSky.WebParts.YouTube
{
    [ToolboxItemAttribute(false)]
    public partial class YouTubeVideo : Microsoft.SharePoint.WebPartPages.WebPart
    {
        public static string YOUTUBERSS = "http://gdata.youtube.com/feeds/api/users/{0}/uploads";

        #region private fields
        private bool IsErrorOnRendering { get; set; }

        private List<SingleVideo> channelVideoList = null;
        #endregion

        #region Controls
        private Panel channelSelection = null;
        private Panel videoContainer = null;
        private DropDownList ddVideos = null;
        private Label lblVideos = null;
        private UpdatePanel ajaxPanel = null;
        private HtmlGenericControl youTubeObject = null;
        #endregion

        public YouTubeVideo()
        {
            IsErrorOnRendering = false;
        }

        #region Overrides

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            channelSelection = new Panel() { ID = "channelSelection" };
            ddVideos = new DropDownList() { ID = "ddVideos", AutoPostBack = true };
            ddVideos.SelectedIndexChanged += new EventHandler(ddVideos_SelectedIndexChanged);
            lblVideos = new Label() { ID = "lblVideos", Text = "Video list:" };
            videoContainer = new Panel() { ID = "videoContainer" };
            ajaxPanel = new UpdatePanel() { ID = "ajaxPanel", Visible=true, UpdateMode=UpdatePanelUpdateMode.Conditional };
        }

        void ddVideos_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ddVideos.SelectedValue))
            {
                if (IFrameEmbedding)
                    youTubeObject.Attributes["src"] = YouTubeManager.IFrameURL(ddVideos.SelectedValue, UseSSL, ShowSimilarVideos);
                else
                    youTubeObject.Attributes["src"] = YouTubeManager.ObjectEmbeddingUrl(ddVideos.SelectedValue, UseSSL, ShowSimilarVideos);
            }
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            base.CreateChildControls();
            if (!IsErrorOnRendering)
            {
                if (IsVideoToShowReady)
                {
                    youTubeObject = YouTubeManager.BuildYoutTubeLink(IFrameEmbedding, VideoWidth, VideoHeight, CurrentVideo, AllowFullScreen, UseSSL, ShowSimilarVideos);
                    if (ShowVideoSelection)
                    {
                        LoadChannelVideos(ChannelName);
                        channelSelection.Visible = ShowVideoSelection;
                        channelSelection.Controls.Add(lblVideos);
                        channelSelection.Controls.Add(ddVideos);
                        ajaxPanel.ContentTemplateContainer.Controls.Add(channelSelection);
                        videoContainer.Controls.Add(youTubeObject);
                        ajaxPanel.Triggers.Add(new AsyncPostBackTrigger { ControlID = ddVideos.ID });
                        ajaxPanel.ContentTemplateContainer.Controls.Add(videoContainer);
                        Controls.Add(ajaxPanel);
                    }
                    else
                    {
                        Controls.Add(youTubeObject);
                    }
                }
                else
                {
                    Controls.Add(new Literal() { Text = "Please define a video to play ..." });
                }
                
            }            
        }

        private void LoadChannelVideos(string channelName)
        {
            ddVideos.Items.Clear();
            ddVideos.Items.Add(new ListItem("Choose a video ...", string.Empty));
            if (channelVideoList == null)
                channelVideoList = YouTubeManager.GetVideoForChannel(channelName);
            if (channelVideoList != null && channelVideoList.Count > 0)
                foreach (SingleVideo video in channelVideoList)
                    ddVideos.Items.Add(new ListItem(video.Title, video.ID));
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!IsErrorOnRendering)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
            IsErrorOnRendering = false;
        }
        #endregion

        private string CurrentVideo
        {
            get
            {
                string currentVideo = VideoLink;
                if (!string.IsNullOrEmpty(ChannelVideoLink))
                    currentVideo = ChannelVideoLink;
                if (ShowVideoSelection && (!string.IsNullOrEmpty(ddVideos.SelectedValue)))
                    currentVideo = ddVideos.SelectedValue;
                return currentVideo;
            }
        }

        private bool IsVideoToShowReady
        {
            get
            {
                return (!string.IsNullOrEmpty(CurrentVideo));
            }
        }

        #region Helper
        private void HandleException(Exception ex)
        {
            this.IsErrorOnRendering = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
        #endregion
    }
}
